import React, { useEffect } from 'react';
import { Select } from 'antd';
import { fetchDatabases } from '@/service/api';

const DatabaseSelector = () => {
  const [options, setOptions] = useState<{ label: string; value: string }[]>();
  const [selectValue, setSelectValue] = useState<string>();

  const handleChange = (value: string) => {
    console.debug(`DatabaseSelector::handleChange ${value}`);
    setSelectValue(value);
  };

  useEffect(() => {
    (async () => {
      let databases = (await fetchDatabases()).data;
      if (databases === null) {
        databases = [] as Bn.Meta.MetaDatabase[];
      }
      const _options = [] as { label: string; value: string }[];
      databases.forEach(ele => {
        _options.push({
          label: `${ele.friendlyName}/${ele.hostName}:${ele.port}`,
          value: ele.id.toString()
        });
      });
      setOptions(_options);
      if (_options.length > 0) {
        setSelectValue(_options[0].value);
      }
    })();
  }, []);

  return (
    <Select
      style={{ width: '100%' }}
      onChange={handleChange}
      value={selectValue}
      options={options}
    />
  );
};

export default DatabaseSelector;
